/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ig.util;

/**
 *
 * @author Ciro
 */
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;



public class TripleDESEncryption {

    public TripleDESEncryption() {
    }

    public static String encrypt(String clearText, String KEY)
            throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, Exception {
        Key key = null;
        byte secret[] = KEY.getBytes();
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
        key = skf.generateSecret(new DESedeKeySpec(secret));
        String cipherTextB64 = "";

        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(1, key);
        byte cipherText[] = cipher.doFinal(clearText.getBytes());
        sun.misc.BASE64Encoder base64encoder = new sun.misc.BASE64Encoder();
        cipherTextB64 = base64encoder.encode(cipherText);

        return cipherTextB64;
    }

    public static String decrypt(String cipherTextB64, String KEY)
            throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, Exception {
        Key key = null;
        byte secret[] = KEY.getBytes();
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
        key = skf.generateSecret(new DESedeKeySpec(secret));
        String clearText = "";
        try {
            Cipher cipher = Cipher.getInstance("DESede");
            sun.misc.BASE64Decoder base64decoder = new sun.misc.BASE64Decoder();
            byte cipherText[] = base64decoder.decodeBuffer(cipherTextB64);
            cipher.init(2, key);
            byte bclearText[] = cipher.doFinal(cipherText);
            clearText = new String(bclearText);
        } catch (NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        } catch (NoSuchPaddingException nspe) {
            nspe.printStackTrace();
        } catch (InvalidKeyException ike) {
            ike.printStackTrace();
        } catch (IllegalBlockSizeException ibse) {
            ibse.printStackTrace();
        } catch (BadPaddingException bpe) {
            bpe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return clearText;
    }

    public static void main(String args[])
            throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, Exception {
        String cipherText = encrypt("cristian", "informaciongerencial.com");
        System.out.println((new StringBuilder()).append("Texto cifrado: ").append(cipherText).toString());
        String clearText = decrypt(cipherText, "informaciongerencial.com");
        System.out.println((new StringBuilder()).append("Texto en claro: ").append(clearText).toString());
    }
}
